<!--
上传组件
@author:何世华
@history：20170920 初始化
-->
<template>
  <div class="sh_upload">
    <div class="sh_upload_item" v-for="(item,index) in cur_val" @tap.stop="!readonly &&select(index)">
      <div class="sh_upload_item_close" @tap.stop="remove(index)" v-if="!readonly">
        &times;
      </div>
      <img :src="item" alt="">
    </div>
    <div class="sh_upload_item sh_upload_add" @tap.stop="select()" v-if="!readonly && cur_val.length < cur_count">

    </div>
    <input type="file" ref="sh_upload_input" hidden @change="add">
  </div>
</template>
<style>
  .sh_upload {
    display: flex;
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    -webkit-flex-wrap: wrap;
    -webkit-box-lines: multiple;
    -moz-flex-wrap: wrap;
    flex-wrap: wrap;
  }

  .sh_upload_item {
    height: 4.5rem;
    width: 4.5rem;
    overflow: hidden;
    -webkit-border-radius: 0.125rem;
    -moz-border-radius: 0.125rem;
    border-radius: 0.125rem;
    background: #f5f5f5;
    position: relative;
    display: flex;
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    align-items: center;
    -webkit-align-items: center;
    -moz-box-align: center;
    -webkit-box-align: center;
    /*border: 1px dashed #cccccc;*/
    margin-right: 1.375rem;
    margin-bottom: 1rem;
  }

  .sh_upload_item:nth-child(3n+0) {
    margin-right: 0;
  }

  .sh_upload_item > img {
    flex: 1;
    -webkit-flex: 1;
    width: 100%;
  }

  .sh_upload_item_close {
    position: absolute;
    right: 0;
    top: 0;
    background-color: rgba(0, 0, 0, 0.4);
    width: 1.1rem;
    line-height: 1.1rem;
    height: 1.1rem;
    color: #ffffff;
    text-align: center;
    font-size: 0.9rem;
    -webkit-border-radius: 0.125rem;
    -moz-border-radius: 0.125rem;
    border-radius: 0.125rem;
  }

  .sh_upload_add {
    border: 1px dashed #cccccc;
    background-color: #fff;
    background-image: url("");
    background-position: center;
    background-repeat: no-repeat;
    -webkit-background-size: 1.5rem 1.2rem;
    background-size: 1.5rem 1.2rem;
  }
</style>
<script>
  import $ from '../lib/zepto/zepto.min';

  export default {
    name: 'sh-upload',
    props: {
      'value': Array,
      'type': String,//类型，image默认，file（未支持）
      'count': Number,//数量
      'readonly': Boolean,
    },
    data() {
      return {
        cur_count: 1,
        cur_val: [],
        edit_index: 0,
      }
    },
    beforeMount() {
    },
    mounted() {
      this.cur_val = this.value || [];
      this.cur_count = this.count || 1;
    },
    updated() {
    },
    methods: {
      init() {
      },
      remove(i) {
//                console.log(i);
        this.cur_val.splice(i, 1);
      },
      select(index) {
//                console.log(index);
        if (index !== undefined) {
          this.edit_index = index;
        } else {
          this.edit_index = -1;
        }
        this.$refs["sh_upload_input"].click();
      },
      add() {
        const reader = new FileReader();
        const file = this.$refs["sh_upload_input"].files[0];
//                console.log(file);
        if (file) {
          reader.readAsDataURL(file);
          reader.onload = (e) => {
            this.getBase64(reader.result, file.type, (data) => {
              let formData = new FormData();
              formData.append("file", this.dataURLtoFile(data.base64, file.name));
              $.ajax({
                url: "/cdma/home/uploadImage",
                type: "POST",
                dataType: "json",
                contentType: false,
                processData: false,
                beforeSend: () => {

                },
                data: formData,
                success: (result) => {
                  if (result.code === 0) {
                    if (this.edit_index === -1) {
                      this.cur_val.push(result.data);
                    } else {
                      this.cur_val.splice(this.edit_index, 1, result.data);
                    }
                  }
                  this.$refs["sh_upload_input"].value = "";
                },
                error: () => {
                  this.$refs["sh_upload_input"].value = "";
                }
              })
            });
          }
        }
      },
      getBase64(blob, fileType, cb) {
        /*return cb && cb({
            base64: blob,
            clearBase64: blob.substr(blob.indexOf(',') + 1)
        });*/

        let img = new Image();
        img.src = blob;
        let obj = {
          width: 800,
          // quality: 1,
        };

        img.onload = function () {
          let that = this;
          //生成比例
          let w = that.width;
          let h = that.height;
          let scale = w / h;

          if (that.width > obj.width) {
            w = obj.width;
          }
          h = w / scale;

          //生成canvas
          var canvas = document.createElement('canvas');
          var ctx = canvas.getContext('2d');
          $(canvas).attr({
            width: w,
            height: h
          });
          ctx.drawImage(that, 0, 0, w, h);

          /**
           * 生成base64
           * 兼容修复移动设备需要引入mobileBUGFix.js
           */
          var base64 = canvas.toDataURL(fileType, obj.quality || 0.8);

          /*!// 修复IOS
          if (navigator.userAgent.match(/iphone/i)) {
              var mpImg = new MegaPixImage(img);
              mpImg.render(canvas, {
                  maxWidth: w,
                  maxHeight: h,
                  quality: obj.quality || 0.8
              });
              base64 = canvas.toDataURL('image/jpeg', obj.quality || 0.8);
          }

          // 修复android
          if (navigator.userAgent.match(/Android/i)) {
              var encoder = new JPEGEncoder();
              base64 = encoder.encode(ctx.getImageData(0, 0, w, h), obj.quality * 100 || 80);
          }*/

          // 生成结果
          var result = {
            base64: base64,
            clearBase64: base64.substr(base64.indexOf(',') + 1)
          };

          cb && cb(result);
        };
      },
      /**
       * base64转file
       * @param dataurl
       * @param filename
       * @returns {*}
       */
      dataURLtoFile(dataurl, filename) {
        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, {type: mime});
      },
    },
    watch: {
      cur_val() {
        this.$emit("input", this.cur_val);
      }
    },
  };
</script>
